package com.uphone.kingmall.wxapi;

import android.app.Activity;
import android.os.Bundle;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.uphone.kingmall.activity.BindPhoneActivity;
import com.uphone.kingmall.activity.personal.set.BindAccountActivity;
import com.uphone.kingmall.app.MyApplication;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.LoginBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.main.MainActivity;
import com.uphone.kingmall.utils.ActivityCollector;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.intent.IntentUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;
    public static int LoginType = 0; // 0 登录   1 绑定微信

    private String unionid;
    private String headimgurl;
    private String nickname;
    private String openid;

    private void getUserMesg(final String access_token, final String openid, final WxUserInfo info) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        LogUtils.e("微信登录提交信息：" + path);
        OkGoUtils.normalRequestGet(path, new onNormalRequestListener() {
            @Override
            public void onSuccess(String json, int code) {
                if (info != null) {
                    info.userInfo(json, openid, access_token);
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtils.e("WXPayEntryActivity");
        api = MyApplication.api;
        api.handleIntent(getIntent(), this);
        super.onCreate(savedInstanceState);
        LogUtils.e("Entry    = == = =   ========= == = = = ");
    }

    @Override
    public void onReq(BaseReq arg0) {
    }

    @Override
    public void onResp(BaseResp resp) {
        LogUtils.e("微信登录transaction" + resp);
        if (resp instanceof SendAuth.Resp) {
            wxLogin(resp);
        } else {
            wechatShare(resp);
            this.finish();
        }
    }

    private void wxLogin(BaseResp resp) {

        wechatLogin(resp, new WxUserInfo() {
            @Override
            public void userInfo(String json, String openid, String access_token) {
                try {
                    JSONObject object = new JSONObject(json);
                    nickname = object.getString("nickname");
                    int sex = Integer.parseInt(object.get("sex").toString());
                    headimgurl = object.getString("headimgurl");
                    if (LoginType == 1) {
                        //绑定微信
                        LoginType = 0;
                        bindWechat(openid, nickname);
                    } else {
                        //登录
                        loginWechat(openid, nickname, headimgurl);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void bindWechat(String openid, String nickname) {

        HttpParams params = new HttpParams();
        params.put("wxid", openid);
        params.put("wxNo", nickname);
        OkGoUtils.normalRequest(MyUrl.bindWx, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    ToastUtils.showShort("绑定成功！");
                    BaseActivity activity = ActivityCollector.getActivity(BindAccountActivity.class);
                    if (activity != null && activity instanceof BindAccountActivity) {
                        ((BindAccountActivity) activity).setWChatBind();
                    }
                    finish();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private void loginWechat(final String openid, final String nickname, final String headimgurl) {
        HttpParams params = new HttpParams();
        params.put("wxId", openid);
        OkGoUtils.normalRequest(MyUrl.loginByWx, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 1) {
                    ActivityCollector.removeAll(MainActivity.class);
                    IntentUtils.getInstance()
                            .with(WXEntryActivity.this, BindPhoneActivity.class)
                            .putInt(ConstansUtils.TYPE, BindPhoneActivity.TYPE_WECHAT)
                            .putString("openid", openid)
                            .putString("nickname", nickname)
                            .putString("headimgurl", headimgurl).start();
                    finish();
                } else if (code == 0) {
                    ToastUtils.showShort("登录成功！");
                    LoginBean bean = GsonUtils.getGson().fromJson(body, LoginBean.class);
                    LoginBean.UserBean user = bean.getUser();
                    if (user == null) {
                        return;
                    }
//                    JpushUtil.setTagAndAlias(WXEntryActivity.this, user.getUserId());
                    SharedPreferencesHelper.saveToken(user.getToken());
                    SharedPreferencesHelper.saveUserName(user.getUserName());
                    SharedPreferencesHelper.saveUserPhone(user.getUserMobile());
                    SharedPreferencesHelper.saveUserId(user.getUserId());
                    SharedPreferencesHelper.saveUserImg(user.getUserPhoto());
//                    JpushUtil.setTagAndAlias(WXEntryActivity.this, user.getUserId());
//                    CommonUtil.loginRY();
                    ActivityCollector.removeAll(MainActivity.class);
                    finish();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    public interface WxUserInfo {
        void userInfo(String json, String openid, String access_token);
    }


    /**
     * 微信分享
     *
     * @param resp
     */
    private void wechatShare(BaseResp resp) {
    }

    /**
     * 微信登录
     *
     * @param resp
     */
    private void wechatLogin(BaseResp resp, final WxUserInfo info) {
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                SendAuth.Resp newResp = (SendAuth.Resp) resp;
                //获取微信传回的code
                String code = newResp.code;
                LogUtils.e("返回的CODE：  " + code);
                String path = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=" + ConstansUtils.WECHAT_APPID
                        + "&secret=" + ConstansUtils.WX_AppSecret
                        + "&code=" + code
                        + "&grant_type=authorization_code";
                LogUtils.e("微信登录提交信息：" + path);
                OkGoUtils.normalRequestGet(path.trim(), new onNormalRequestListener() {
                    @Override
                    public void onSuccess(String json, int code) {

// {"access_token":"6_9DaAe7zma1MVS1WNHAyWJIE0LzKY5SiR1iUBdPAn-9g5uQOSYJ22YY6AYCVGpw5mYKQCMZKK0-8cHRikCiGETNLjC3DVNwJ69cpbW24UDDc",
// "expires_in":7200,"refresh_token":"6_rnG-a-5LalTtR3Mvh2238C-DfZmtai-bVevf37dYBCYqLgh4VD5a2Ah-jTH_JODxV0FN1FGOGRwKSGjrReeXYP-5zboXKdu3sZvXELmbV_A",
// "openid":"oOyMAwgY9MN29x3mvHXUh-ZANWuM",
// "scope":"snsapi_userinfo",
// "unionid":"oCXUewvC4ajs9I2nJLN0azYlIaco"}
                        LogUtils.e("微信登录：" + json);
                        try {
                            JSONObject object = new JSONObject(json);
                            openid = object.getString("openid").toString().trim();
                            unionid = object.getString("unionid").toString().trim();
                            String access_token = object.getString("access_token").toString().trim();
                            LogUtils.e("获得的 openid：  " + openid + " unionid " + unionid);
                            getUserMesg(access_token, openid, info);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        finish();
                    }

                    @Override
                    public void onError(Response<String> response) {

                    }
                });
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                ToastUtils.showShort("登录取消");
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                ToastUtils.showShort("登录失败");
                finish();
                break;

        }
    }
}
